import axios from 'axios'
// import { Message, MessageBox } from 'element-ui'
import { Message } from 'element-ui'
// import store from '../store'
import { getToken } from '@/utils/auth'

const baseUrl = 'http://space-api.icaremgt.com'
// const baseUrl = 'https://space-api.check.icaremgt.com'

// 创建axios实例
const service = axios.create({
  baseURL: baseUrl, // 本地
  timeout: 60000 // 请求超时时间
  // withCredentials: true
})
service._baseURL = baseUrl
// request拦截器
service.interceptors.request.use(config => {
  console.log('TOKEN=' + getToken())
  if (getToken()) {
    config.headers['x-token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 510 || res.code === 1004 || res.code === 1002 || res.code === 500) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
    } else if (res.code === 1009) {
      window.location.href = baseUrl + '/wxoauth/route?redirect_uri=' + encodeURIComponent(window.location.href)
    } else if (res.code === 1006) {
      Message({
        message: '您因长时间逗留，验证已过期，正在刷新！',
        type: 'error',
        duration: 5 * 1000
      })
      setTimeout(() => {
        window.location.href = window.location.href.replace('code', 'a')
      }, 1500)
    } else {
      return res
    }
  },
  error => {
    console.log('错误' + error)
    if (error.response && error.response.data && error.response.data.message) {
      error.message = error.response.data.message
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
